package com.costeaalex.datedrivenfilecopy.model.copiers;

/**
 * @author Alex Costea
 * 
 * Class that handles copying operations over FTP.
 * 
 */

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.commons.net.ftp.FTPClient;

import com.costeaalex.datedrivenfilecopy.model.interfaces.ICopier;

public class FTPCopier implements ICopier {
	
	private String[] connectionData;
	private FTPClient FTPC;
	
	public FTPCopier(String[] connectionData) {
		this.connectionData=connectionData;
	}
	
	@Override
	public void init() {
		FTPC=new FTPClient();
		try {
			FTPC.connect(connectionData[0]);
			FTPC.login(connectionData[1], connectionData[2]);
		}
		catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	@Override
	public boolean copyDirectory(String path) {
		try {
			FTPC.makeDirectory(path);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public boolean copyFile(String fromPath, String toPath) {
		FileInputStream fIS;
		try {
			fIS = new FileInputStream(fromPath);
			FTPC.storeFile(toPath.replace("\\", "/"), fIS);
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		}
		catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		
	}

	@Override
	public void destroy() {
		if(FTPC!=null)
			try {
				FTPC.logout();
				FTPC.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}

}
